<?php

namespace app\controller\api;

use app\service\UserDeviceBindingService;
use app\service\UserDeviceShareService;
use app\validate\MqttValidate;
use share\controller\ApiBaseController;
use share\service\AmqpService;
use share\service\UserBaseService;
use think\Log;

class MqttController extends ApiBaseController{

    public function initValidate(){
        $this->validate = new MqttValidate();
    }

    /**
     * mqtt 用户绑定变更消息
     * topic：/${productKey}/${deviceName}/thing/awss/enrollee/user
     */
    public function bind_change_action(){
        // trace("MQTT_bindChange:".json_encode($this->request->param()),Log::ERROR);
        $input = $this->check();
        $relationUser = $this->request->param('identityInfos');
        $bind = $this->request->param('bind');
        $iotId = $input['iotId'];
        $region = $input['region'];

        // 更新设备基本信息
        AmqpService::simplePush(
            [
                'service' => 'app\\service\\DeviceBaseService@upsetByPkDnMqtt',
                'params' => [
                    'pk' => $input["productKey"],
                    'dn' => $input["deviceName"],
                    'iot_id' => $iotId,
                    "server_site" => $region,
                ],
            ]
        );

        $unshareUser = []; //删除分享的用户
        foreach($relationUser as $user){
            $tmpUser = $this->check('relationUser',$user);
            if($tmpUser['owned'] == 1){ // 如果是主账号  只有一个         
                if(!$bind){ // 解绑
                    UserDeviceBindingService::unbindByIotId($iotId);                    
                }
                else{// 绑定
                    UserDeviceBindingService::deviceChangeBindUser($iotId,$tmpUser['identityId']);
                }
            }
            else{ // 分享者账号
                if(!$bind){ // 删除分享  添加分享  没有分享规则 不处理
                    $unshareUser[] = $tmpUser['identityId'];                                  
                }
            }
        }
        // if(empty($adminUser)){// 没有管理员用户
        //     trace("MQTT_bindChange:do not have owned user",Log::ERROR);
        //     return self::fail("do not have owned user");
        // }
        if(count($unshareUser) > 0){            
            $users = UserBaseService::getAllByFilter(['identity_id' => ['in',$unshareUser ]]);
            $params = [];
            foreach($users  as $user){
                $params[] = [
                    'uid' => $user['id'],
                    'mainId' => $iotId,
                ];
            }
            if(count($params) > 0){
                UserDeviceShareService::deleteAllShareByDevice($params); 
            } 
        }
        return self::ok($input);
    }
}